﻿using System;
using System.Data.SqlClient;
using Co9320.NamaAlert.Server.Parameters;

namespace Co9320.NamaAlert.Server.BackEnd
{
	internal class ModifyProcess : ProcessObject
	{
		private static int MaxTransaction = Co9320.NamaAlert.Server.Properties.Settings.Default.MaxTransactionOfModify;

		private ModifyParameter Parameter_;
		private SqlParameter ft;
		private SqlParameter tt;

		public ModifyProcess(ModifyParameter Parameter)
			: base(Parameter)
		{
			if (Parameter.Tags == null)
			{
				throw new ArgumentException("Tags is null");
			}

			this.Parameter_ = Parameter;

			ProcessObject.TrimValue(Parameter_.Tags, MaxTransaction);

			base.cmd.CommandText = "EXECUTE dbo.ModifyTag @sid,@cstr,@ft,@tt;";
			ft = new SqlParameter("@ft", System.Data.SqlDbType.NVarChar);
			tt = new SqlParameter("@tt", System.Data.SqlDbType.NVarChar);

			cmd.Parameters.Add(ft);
			cmd.Parameters.Add(tt);
		}


		public override void DoProcess()
		{
			foreach (ModifyPair elem in Parameter_.Tags)
			{
				if (elem.ModifyFrom == null || elem.ModifyFrom.Length > ProcessObject.MaxCharacterLength)
				{
					continue;
				}

				if (elem.ModifyTo == null || elem.ModifyTo.Length > ProcessObject.MaxCharacterLength)
				{
					continue;
				}

				ft.Value = elem.ModifyFrom;
				tt.Value = elem.ModifyTo;

				cmd.ExecuteNonQuery();
			}

			base.Dispose(true);
		}
	}


}